import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/message_api.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/repositories/message_repository.dart';
import 'package:sainbainu/common/routes/routes.dart';

import 'index.dart';

class LikeCollectController extends GetxController {
  LikeCollectController();

  final state = LikeCollectState();

  @override
  void onInit() {
    super.onInit();
    state.refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    state.messageRepository = MessageRepository(MessageApi());
    state.pagerRequest = PagerRequest();

    getList();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    state.refreshController.dispose();
  }

  /// 获取内容列表
  Future getList({bool refresh = true}) async {
    if (refresh) {
      state.pagerRequest.pageNum = 1;
    }
    var res = await state.messageRepository.likeCollectionList(
      state.pagerRequest,
    );
    if (refresh) {
      state.list.rows = res.rows;
    } else {
      state.list.rows.addAll(res.rows);
    }

    state.list.total = res.total;
    state.hasMore =
        state.pagerRequest.pageNum * state.pagerRequest.pageSize < res.total;
    state.pagerRequest.pageNum++;
    update(['like_collec']);
  }

  /// 下拉刷新
  Future onRefresh() async {
    try {
      await getList();
      if (state.list.rows.isEmpty) {
        state.refreshController.finishRefresh(IndicatorResult.noMore);
      } else {
        state.refreshController.finishRefresh(IndicatorResult.success);
      }
      state.refreshController.resetFooter();
    } catch (e) {
      state.refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  /// 上拉下载
  Future onRichBottom() async {
    try {
      if (state.hasMore) {
        await getList(refresh: false);
      }
      if (!state.hasMore) {
        state.refreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.refreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 用户详情页
  toUserDetailPage(int? customerId) {
    if (customerId == null) return;
    Get.toNamed(AppRoutes.userDetail, arguments: {'customerId': customerId});
  }

  /// 内容详情页
  toContentDetailPage(int? noteId) {
    if (noteId == null) return;
    Get.toNamed(AppRoutes.contentDetail, arguments: {'noteId': noteId});
  }
}
